package com.ch.ms.server.base;

import com.ch.ms.server.base.client.MapleClientSession;
import com.ch.ms.server.base.tools.ChannelUtils;
import com.ch.ms.server.packet.MaplePacket;
import com.ch.ms.server.packet.MaplePacketHeader;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.Map;


@Slf4j
public class MapleServerHandler extends SimpleChannelInboundHandler<MaplePacket> {


    private Map<MaplePacketHeader, MaplePacketHandler> packetHandlers;

    public MapleServerHandler(Map<MaplePacketHeader, MaplePacketHandler> packetHandlers) {
        this.packetHandlers = packetHandlers;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);

        //新的连接激活时同时创建客户端会话
        ChannelUtils.createMapleClientSession(ctx.channel());
        log.info("创建会话 {}", ChannelUtils.getMapleClientSession(ctx.channel()));
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

        MapleClientSession session = ChannelUtils.getMapleClientSession(ctx.channel());
        log.info("移除会话 {}", session);
        ChannelUtils.removeMapleClientSession(session);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MaplePacket maplePacket) throws Exception {


        MapleClientSession session = ChannelUtils.getMapleClientSession(ctx.channel());
        log.info("会话 {} 正在处理消息 {}", session, maplePacket);
        if (CollectionUtils.isEmpty(packetHandlers) || !packetHandlers.containsKey(maplePacket.getHeader()))
            log.error("无法处理消息 {} ,未设置消息处理器", maplePacket);
        else
            packetHandlers.get(maplePacket.getHeader()).handle(session, maplePacket);

    }
}
